/**
 * Created by hjqi on 2016/4/26.
 */
var express = require('express');
var router = express.Router();
/*var libK8s = require('../lib/k8s/kubernetes');
var _k8s = new libK8s();*/
var _k8s_adp = require('../lib/k8s/k8sAdpter');
//volume service use  default cluster
//var _k8s = _k8s_adp.getK8s();

//db part
var storageMetaInfoDB = require('../db/storageMetaInfoDB');
var _storageinfo = new storageMetaInfoDB();

var httpRequest = require('../lib/common/httpRequest').httpRequest,
    myRet = require('../lib/common/common').myReturn;
var _req = new httpRequest();
var request = require('request');
var path = require('path');
var fs =  require('fs');
var storageAdpt = require('../lib/storage/storageAdapter');
var _handle = storageAdpt.getStorageHandle();
/**
 * 查询存储信息volume（包括hostpath 和glusterfs）
 */
router.get('/getstorages',function(req, res, next){
    //get all the 'glusterfs' type volume record
    var _username = req.username;
    var volumeType = req.query.volumeType;
    var volumeName = req.query.name;

    if( volumeType && volumeType=="hostpath"){
        //跟据查询参数是否有volumetype来判断是否是自由主机
        _storageinfo.getWithParam(null,{namespace:_username,
                volumeType:"hostPath"},function(err,rets){
            if(err){
                res.status(400).send(myRet(false,err.message,err.message));
                logger.error("exec query error:"+JSON.stringify(err) ) ;
            }
            else
                res.send(myRet(true,undefined,rets));
        });
    }else{
        var _queryParam = {namespace:_username,
            volumeType :
            { $exists:false}
        };
        if(volumeName !== undefined)
            _queryParam.name = volumeName;

        /*if(req.query.app)
            _queryParam.mountAppNameArray = {$in:[req.query.app]};*/

        _storageinfo.getWithParam(null,_queryParam,function(err,rets){
            if(err)
                res.status(400).send(myRet(false,err.message,err.message));
            else
                res.send(myRet(true,undefined,rets));
        });
    }

})

router.post('/createstorage',function(req, res, next){
    var param = req.body;
    var _username = req.username;
    var _volumn = param.sid;
    var size=param.size;
    var date=param.date;


    //_handle.createVolumeWithCheckEndpoints(_username,_volumn).then(function(ret){
    _handle.createVolume(_username,{volumeName:_volumn,volumeSize:size,createDate:date}).then(function(ret){
        res.send(ret);
    }).catch(function(err){
        err.data = err.error;
        res.send(err);
    });

})

router.post('/delstorage',function(req, res, next){
    var item = req.body;
    var _username = req.username;

    _handle.deleteVolume(item).then(function(ret){
        res.send(ret);
    }).catch(function(err){
        res.status(400).send(err);
    });
})

router.get('/getfiles',function(req, res, next){
    var param = req.query;
    var _username = req.username;
    var _volumn = param.name;
    /*_storageinfo.getWithParam(null,{storagename:param.name},function (err,rets) {
        if (err) {
            res.status(400).send(err.message);
        } else {
            res.send(rets);
        }
    });*/
    _handle.listFiles(_username+'-'+_volumn).then(function(rets){
        res.send(rets);
    }).catch(function(err){
        res.status(400).send(err);
    });
})

router.post('/uploadfile',function(req, res, next){

    var param = req.query;
    var _username = req.username;
    var _volumn = param.sid;

    try{

        var filename = req.files.files.originalFilename || path.basename(req.files.files.ws.path);
        var buf = fs.readFileSync(req.files.files.path);
        _handle.upload(_username+'-'+_volumn,filename,buf).then(function(ret){
            if(ret)
                res.send({
                    ret:true,
                    filename:filename
                })
            else
                res.status(400).send('upload error');
        }).catch(function(err){
            res.status(400).send('upload error');
        });

    }catch(e){
        console.log(e);
    }

})

router.post('/delfiles',function(req, res, next){
    var param = req.body;
    var _username = req.username;
    var _volumn = param.vol;
    var _filename = param.file;
    /*_storageinfo.getWithParam(null,{storagename:param.name},function (err,rets) {
     if (err) {
     res.status(400).send(err.message);
     } else {
     res.send(rets);
     }
     });*/
    _handle.deleteFile(_username+'-'+_volumn,_filename).then(function(ret){
        if(ret)
            res.send({
                ret:true
            });
        else
            res.send({
                ret:false
            });
    }).catch(function(err){
        res.status(400).send(e);
    });
})
router.get('/getStorageDetail',function (req,res,next) {
    var param=req.query;
    var _username=req.username;
    var volume={};
    volume.volumeId=_username+'-'+param.name;
    volume.namespace=_username;
    _handle._usedImage(volume).then(function (ret) {
        if( ret.ret == true && ret.data !== undefined ){
            res.send(ret.data);
        }else
            res.status(400).send(ret.data);
    }).catch(function(err){
        res.status(400).send(err);
    });
})
router.get('/chkVolMgrSvcExist',function(req, res, next){
    var param = req.query;
    var _username = req.username;
    var _volume = _username+'-'+param.name;

    _handle.IsExistVolSvc(_username,_volume).then(function(ret){
        if( ret.ret == true && ret.data !== undefined && ret.data.svcId !== undefined ){
            res.send({
                ret:true,
                svcId:ret.data.svcId
            });
        }else if( ret.ret == false ){
            res.status(400).send(ret.data);
        }
        else{
            res.send({
                ret:false
            });
        }
    }).catch(function(err){
        res.status(400).send(err);
    });

})

router.post('/createVolMgrSvc',function(req,res,next){
    var param = req.body;
    var _username = req.username;
    var _volume = param.volume;

    _k8s_adp.getK8s().then(function(_k8s){
        return _k8s.createVolMgrSvc(_username,_volume);
    }).then(function(ret){
        res.send(ret);
    }).catch(function(err){
        res.status(400).send(err);
    });
});

router.post('/operateVolMgrSvc',function(req,res,next){
    var param = req.body;
    var _username = req.username;
    var _volumnSvc = param.volume;

    //hard code for rc name
    //_k8s.modifyReplicationController(_username,_volumn+'-v1.0',_rcnum).then(function(ret){
    //TODO change job
    _k8s_adp.getK8s().then(function(_k8s){
        return _k8s.startJob(_username,_volumnSvc);
    }).then(function(ret){
        if(ret.code === undefined)
            res.send(true);
        else if(ret.code === 404)
            res.status(400).send(ret.message);
        else
            res.send(false);
    }).catch(function(err){
        res.status(400).send(err);
    });
});

router.get('/checkVolumeExist',function(req,res,next){

    var param = req.query;
    var _username = req.username;
    var _volumn = param.name;

    _handle.isExistVolumeInServer(_username+'-'+_volumn).then(function(ret){
            res.send(ret)
        })
        .catch(function(err){
            res.status(400).send(err);
        });
});

module.exports = router;